#include <iostream>
#include <algorithm>
using namespace std;

class Solution 
{
public:
    int trap(int A[], int n)
	{
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if(n<=2)
			return 0;
		int water = 0;

		int* leftMax = new int[n];
		int* rightMax = new int[n];

		leftMax[0] = A[0];
		rightMax[n-1] = A[n-1];
		for(int i=1;i<n;i++)
		{
			leftMax[i] = max(A[i],leftMax[i-1]);
			rightMax[n-1-i] = max(A[n-i-1],rightMax[n-i]);
		}

		for(int i=0;i<n;i++)
			water += (min(leftMax[i],rightMax[i])-A[i]);

		return water;
    }
};


int main()
{
	int n;
	Solution s;

	while(cin>>n)
	{
		if(n<=0)
			break;

		int* A = new int[n];
		for(int i=0;i<n;i++)
			cin>>A[i];

		cout<<s.trap(A,n)<<endl;
	}
}
